package com.class05.config;

import com.github.pagehelper.PageInterceptor;
import org.apache.ibatis.logging.slf4j.Slf4jImpl;
import org.apache.ibatis.session.AutoMappingBehavior;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.util.Properties;

/**
 * @ClassDescription: 持久层配置类：连接池、sqlSessionFactory，Mapper代理对象
 * @JdkVersion: 17
 * @Author: yxy
 * @Created: 2023/12/21 14:59
 * 方式1：保留外部配置文件
 * todo ：如果dataSource和mybatis的组件配置到一起，出现@Value注解不生效
 *   原因：mybatis的组件优先加载，@Value还没有读取！
 *   解决：分开配置，写到不同的类即可！
 */
@Configuration
public class MapperJavaConfigNew {
    @Bean
    public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource) {
        SqlSessionFactoryBean sqlSessionFactoryBean =
                new SqlSessionFactoryBean();
        //指定配置文件等信息
        //指定数据库莲池对象
        sqlSessionFactoryBean.setDataSource(dataSource);

        org.apache.ibatis.session.Configuration configuration
                = new org.apache.ibatis.session.Configuration();
         /*<!--  开启二级缓存     -->
        <setting name="cacheEnabled" value="true"/>*/
        configuration.setCacheEnabled(true);
//      <!--  开启驼峰映射      -->
//      <setting name="mapUnderscoreToCamelCase" value="true"/>
        configuration.setMapUnderscoreToCamelCase(true);
//      <setting name="logImpl" value="SLF4J"/>
        configuration.setLogImpl(Slf4jImpl.class);
         /*<!-- 开启resultMap自动映射       -->
        <setting name="autoMappingBehavior" value="FULL"/>*/
        configuration.setAutoMappingBehavior(AutoMappingBehavior.FULL);
        sqlSessionFactoryBean.setConfiguration(configuration);
        //别名设置
//      <typeAliases>
//        <!--   给实体类起别名     -->
//        <package name="com.class05.pojo"/>
//      </typeAliases>
        sqlSessionFactoryBean.setTypeAliasesPackage("com.class05.pojo");
        PageInterceptor pageInterceptor = new PageInterceptor();
        Properties properties = new Properties();
//          <!--    插件语法对应的数据类型        -->
//            <property name="helperDialect" value="mysql"/>
        properties.setProperty("helperDialect", "mysql");
        pageInterceptor.setProperties(properties);

        sqlSessionFactoryBean.addPlugins(pageInterceptor);

        return sqlSessionFactoryBean;
    }

    //mapper代理对象加入到ioc
    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer() {
        //Mapper代理对象的factoryBean->指定一个包->mapper接口->sqlSessionFactory->
        // ->sqlSession->getMapper->mapper代理对象->ioc
        MapperScannerConfigurer mapperScannerConfigurer =
                new MapperScannerConfigurer();
//        mapper接口和mapperxml所在共同包
        mapperScannerConfigurer.setBasePackage("com.class05.mapper");
        return mapperScannerConfigurer;
    }

}
